﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;

namespace utils
{
    class HttpUtils
    {

        public static String Login(String license, String companyId)
        {
            string apiUrl = $"{ConfigurationManager.AppSettings.Get("getByLicense")}?license={license}";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
            request.Headers["companyId"] = companyId;
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;


            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception e)
            {
                Console.WriteLine("params: {0}", e.ToString());
                return null;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }

        }

        public static Stream ExportPdf(String token, String printTemplateId, String paramStr, bool isMdmPrint)
        {
            string serviceUrl = $"{ConfigurationManager.AppSettings.Get("exportPdf")}?templateId={printTemplateId}&data={paramStr}&isMdmPrint={isMdmPrint}";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.Headers["X-Auth-Token"] = token;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            return myResponseStream;
        }

    }
}
